#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

const char* ssid = "ZXC-AP";
const char* password = "ZXCzxc123...";
const char* mqtt_server = "192.168.1.2";

WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE	(50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  // Serial.print("收到数据来自[");
  // Serial.print(topic);
  // Serial.print("] ");
  /*逐个发送*/
  Serial.printf("%c%c",0xff,0xff);//帧头
  for (int i = 0; i < length; i++) {
    //Serial.print((char)payload[i]);
    Serial.printf("%c",payload[i]);
  }
  Serial.printf("\n");//帧尾
  /*解析数据*/
  // uint16_t ch1,ch2,ch3;
  // ch1 += payload[0] << 8;
  // ch1 += payload[1];
  // ch2 += payload[2] << 8;
  // ch2 += payload[3];
  // ch3 += payload[4] << 8;
  // ch3 += payload[5];
  // Serial.printf("%05d,%05d,%05d",ch1,ch2,ch3);
  // Serial.println();




  /*根据收到的内容控制LED*/
  // 如果收到的第一个字符是 1，则打开 LED 指示灯
  // if ((char)payload[0] == '1') {
  //   digitalWrite(BUILTIN_LED, LOW);   // 打开 LED 指示灯（注意 LOW 是电压水平
  //   // 但实际上 LED 亮着;这是因为
  //   // 在 ESP-01 中为低电平有效）。
  // } else {
  //   digitalWrite(BUILTIN_LED, HIGH);  // 将电压设为高电平，关闭发光二极管
  // }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected!");

      /*发布消息*/
      //client.publish("outTopic", "hello world");
      
      /*订阅主题*/
      client.subscribe("logic");
      digitalWrite(BUILTIN_LED, LOW);//连接成功LED亮
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  digitalWrite(BUILTIN_LED, HIGH);
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {

  if (!client.connected()) {
    /*如果断开与服务器的连接熄灭LED*/
    digitalWrite(BUILTIN_LED, HIGH);
    reconnect();
  }
  client.loop();

  /*定时发送数据*/
  // unsigned long now = millis();
  // if (now - lastMsg > 2000) {
  //   lastMsg = now;
  //   ++value;
  //   snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
  //   Serial.print("Publish message: ");
  //   Serial.println(msg);
  //   client.publish("outTopic", msg);
  // }
}